﻿using System;
using System.Web.Mvc;

using mvcForum.Core.Abstractions.Interfaces;

namespace mvcForum.Web.Filters {

	public class ConfigurationControlledAttribute : ActionFilterAttribute {
		private ConfigurationArea area;
		private String name;

		public ConfigurationControlledAttribute(ConfigurationArea area, String name)
			: base() {

			this.area = area;
			this.name = name;
		}

		public override void OnActionExecuting(ActionExecutingContext filterContext) {
			base.OnActionExecuting(filterContext);

			if (filterContext == null) {
				throw new ArgumentNullException("filterContext");
			}

			if (filterContext.Controller != null) {
				try {
					IConfiguration config = DependencyResolver.Current.GetService<IConfiguration>();

					Boolean result = false;

					switch (this.area) {

						case ConfigurationArea.AccountController:
							result = config.UseForumAccountController;

							if (result && !String.IsNullOrWhiteSpace(name)) {

								switch (this.name) {

									case "SignUp":
										result = config.AllowLocalUsers && config.AllowSignUp;
										break;

									case "Local":
										result = config.AllowLocalUsers;
										break;

									case "OpenAuth":
										result = config.AllowOpenAuthUsers;
										break;

									case "LocalOrOpenAuth":
										result = config.AllowOpenAuthUsers || config.AllowLocalUsers;
										break;

									default:
										throw new ApplicationException("name");
										break;
								}
							}
							break;

						default:
							throw new ArgumentException("area");
					}

					if (!result) {
						filterContext.Result = new HttpNotFoundResult();
					}
				}
				catch { }
			}
		}
	}
}